package cn.glinks.liuhe.activity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

import butterknife.BindView;
import butterknife.OnClick;
import cn.glinks.liuhe.R;
import cn.glinks.liuhe.adpter.SwipeDeckAdapter;
import cn.glinks.liuhe.api.ApiConstants;
import cn.glinks.liuhe.api.ApiRequest;
import cn.glinks.liuhe.api.jsonbean.TestResult;
import cn.glinks.liuhe.api.jsonbean.UserInfo;
import cn.glinks.liuhe.api.parser.GlkProtocolParser;
import cn.glinks.liuhe.app.AppApplication;
import cn.glinks.liuhe.base.BaseActivity;
import cn.glinks.liuhe.baserx.RxSubscriber;
import cn.glinks.liuhe.model.Question;
import cn.glinks.liuhe.utils.ActTransAnimUtils;
import cn.glinks.liuhe.utils.AppCommonUtils;
import cn.glinks.liuhe.utils.CountDownTimer;
import cn.glinks.liuhe.utils.GsonUtils;
import cn.glinks.liuhe.utils.TimeTransformUtils;
import cn.glinks.liuhe.utils.ToastUtils;
import cn.glinks.liuhe.widget.iOSDialog;
import cn.glinks.liuhe.widget.swipedeck.SwipeDeck;

public class MainActivity extends BaseActivity {

    // 页面1-做题页面
    @BindView(R.id.include_main_1)
    LinearLayout mIncludeMainPagerOne;

    @BindView(R.id.btn_cancel)
    Button mPagerOneCancelButton;

    @BindView(R.id.tv_time)
    TextView mPagerOneTimeText;

    @BindView(R.id.swipe_deck)
    SwipeDeck mCardStack;

    @BindView(R.id.btn_no)
    Button mPagerOneNoButton;

    @BindView(R.id.btn_yes)
    Button mPagerOneYesButton;

    @BindView(R.id.btn_complete)
    Button mPagerOneCompleteButton;

    // 页面2-结果页面
    @BindView(R.id.include_main_2)
    LinearLayout mIncludeMainPagerTwo;

    @BindView(R.id.iv_result_tip)
    ImageView mPagerTwoResultImage;

    @BindView(R.id.tv_completed_sum)
    TextView mPagerTwoSumText;

    @BindView(R.id.tv_remain_time)
    TextView mPagerTwoTimeText;

    // 变量
    private UserInfo mUserInfo;
    private long mTestTime = 60000 * 60;// 测评限制时间

    // 倒计时相关
    private int mUsedTime = 0;// 测评花费时间(单位s)
    private String mRemainTime = "";// 测评剩余时间字符串
    private CountDownTimer mCountDownTimer;

    // 问题卡相关
    private SwipeDeckAdapter mSwipeDeckAdapter;// 卡片效果适配器
    private List<Question> mQuestionList = new ArrayList<>();// 题目缓存
    private int mQuestionSum = 0;// 题目总数
    private int mQuestionCurrentIndex = 0;// 当前题目Index(从0开始,第一页题目卡片的index是0)
    private List<TestResult> mResultList = new ArrayList<>();// 测评结果

    @Override
    public int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        // 设置为透明状态栏
        SetTranslanteBar();
        // 加载用户信息
        mUserInfo = ((AppApplication)getApplicationContext()).getLoginUser();
        // 初始化所有页面
        initAllPager();
        // 显示开始测评页面
        switchPagerTo(1);
    }

    private void initAllPager() {
        /************************
         *  初始化测评页面
         ************************/
        // 显示隐藏相关按钮
        mPagerOneCompleteButton.setVisibility(View.GONE);
        mPagerOneNoButton.setVisibility(View.VISIBLE);
        mPagerOneYesButton.setVisibility(View.VISIBLE);
        // 设置倒计时时间文本
        String testTimeText = TimeTransformUtils.dateToStr("HH:mm:ss", new Date(mTestTime));
        mPagerOneTimeText.setText(testTimeText);
        // 加载试题数据
        String msg = ((AppApplication) getApplicationContext()).getQuestions();
        GlkProtocolParser.parseGetQuestions(msg, mQuestionList);
        mQuestionSum = mQuestionList.size();
        mQuestionCurrentIndex = 0;
        // 初始化试题卡片控件
        initSwipeDeck();
        // 开始倒计时
        mUsedTime = 1;
        mCountDownTimer = startCountDownTimer(mTestTime);
        mCountDownTimer.start();

        /************************
         *  初始化测评结束页面
         ************************/
        //TODO:
    }


    /**
     * Des:初始化答题卡控件
     */
    private void initSwipeDeck() {
        // 设置适配器
        mSwipeDeckAdapter = new SwipeDeckAdapter(mQuestionList, this);
        mCardStack.setAdapter(mSwipeDeckAdapter);

        // 设置SwipeDeck回调接口
        mCardStack.setCallback(new SwipeDeck.SwipeDeckCallback() {
            @Override
            public void cardSwipedLeft(long stableId) {
                //LogUtils.logd("card was swiped left, position in adapter: " + stableId);
            }

            @Override
            public void cardSwipedRight(long stableId) {
                //LogUtils.logd("card was swiped right, position in adapter: " + stableId);
            }

        });

        // 设置SwipeDeck的左右滑动图标
        mCardStack.setLeftImage(R.id.iv_left_image);
        mCardStack.setRightImage(R.id.iv_right_image);
    }

    /*--------------------------------------------------------------------------------
     *                          本Activity的一些封装函数
     ---------------------------------------------------------------------------------*/
    /**
     * Des:切换到不同页面
     * @param index 页面索引
     */
    private void switchPagerTo(int index) {
        if(index == 1) {//测评页面
            mIncludeMainPagerOne.setVisibility(View.VISIBLE);
            mIncludeMainPagerTwo.setVisibility(View.GONE);
        } else if(index == 2) {//测评结束页面
            mIncludeMainPagerTwo.setVisibility(View.VISIBLE);
            mIncludeMainPagerOne.setVisibility(View.GONE);
        }
    }

    /**
     * Des:开始答题倒计时(计时间隔默认为1s)
     * @param startTime 计时起始时间(单位ms)
     */
    private CountDownTimer startCountDownTimer(final long startTime) {
        CountDownTimer countDownTimer = new CountDownTimer(startTime, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                // 记录话费时间
                mUsedTime++;
                // 设置倒计时文本
                SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
                format.setTimeZone(TimeZone.getTimeZone("GMT"));
                Date d1 = new Date(startTime - millisUntilFinished);
                mRemainTime = format.format(d1);
                mPagerOneTimeText.setText(mRemainTime);
            }

            @Override
            public void onFinish(long millisUntilFinished) {
                iOSDialog.showRadioDialog(MainActivity.this, "提示", "时间已到, 请返回并重新答题",
                        new iOSDialog.DialogClickListener() {
                            @Override
                            public void confirm() {
                                // 返回重新测评页面
                                ActTransAnimUtils.finishActionSlideLeftToRight(MainActivity.this);
                                if (false) {
                                    String sum = String.format("%03d", mQuestionCurrentIndex);
                                    mPagerTwoSumText.setText(sum + "/315");
                                    mPagerTwoTimeText.setText("剩余时间: 00:00:00");
                                    mPagerTwoResultImage.setImageResource(R.drawable.ic_test_timeout);
                                    switchPagerTo(2);
                                    // 发送网络请求
                                    mRxManager.add(ApiRequest.requestCommitAnswer(mUserInfo.getJwt(),
                                            mUserInfo.getTestTask().getTestTaskId()+"", mUsedTime, mQuestionList)
                                            .subscribe(new RxSubscriber<String>(mContext) {
                                                @Override
                                                protected void _onNext(String msg) {
                                                    // 响应处理
                                                    if (GsonUtils.getIntValue(msg, "error") == 0) {
                                                        ToastUtils.showShort("提交答案成功");
                                                    } else {
                                                        String reason = GsonUtils.getValue(msg, "reason");
                                                        ApiConstants.showError(reason);
                                                    }
                                                }

                                                @Override
                                                protected void _onError(String message) {
                                                    // TODO:处理失败响应
                                                    ToastUtils.showShort("提交答案失败:" + message);
                                                }
                                            }));
                                }

                            }

                            @Override
                            public void cancel() {

                            }
                        });
            }
        };
        countDownTimer.start();

        return countDownTimer;
    }

    /*--------------------------------------------------------------------------------
     *                          点击事件接口实现
     ---------------------------------------------------------------------------------*/
    // 是(PageTwo)
    @OnClick(R.id.btn_yes)
    public void clickYes() {
        Question qst = mQuestionList.get(mQuestionCurrentIndex);
        qst.answer = Question.YES;
        // 判断是否为最后一题
        if (mQuestionCurrentIndex < (mQuestionSum - 1)) {
            // 不是,自动切换到下一题
            mCardStack.swipeTopCardRight(200);
            mQuestionCurrentIndex++;
        } else {
            // 是,隐藏是否按钮,显示完成按钮
            mPagerOneYesButton.setClickable(false);
            mPagerOneNoButton.setClickable(false);
            mPagerOneYesButton.setVisibility(View.GONE);
            mPagerOneNoButton.setVisibility(View.GONE);
            mPagerOneCompleteButton.setVisibility(View.VISIBLE);
            mPagerOneCompleteButton.setClickable(true);
        }
    }

    // 否(PageTwo)
    @OnClick(R.id.btn_no)
    public void clickNo() {
        Question qst = mQuestionList.get(mQuestionCurrentIndex);
        qst.answer = Question.NO;
        // 判断是否为最后一题
        if (mQuestionCurrentIndex < (mQuestionSum - 1)) {
            // 不是,自动切换到下一题
            mCardStack.swipeTopCardRight(200);
            mQuestionCurrentIndex++;
        } else {
            // 是,隐藏是否按钮,显示完成按钮
            mPagerOneYesButton.setClickable(false);
            mPagerOneNoButton.setClickable(false);
            mPagerOneYesButton.setVisibility(View.GONE);
            mPagerOneNoButton.setVisibility(View.GONE);
            mPagerOneCompleteButton.setVisibility(View.VISIBLE);
            mPagerOneCompleteButton.setClickable(true);
        }
    }

    // 完成答题(PageTwo)
    @OnClick(R.id.btn_complete)
    public void clickComplete() {
        // 关闭倒计时功能
        if (mCountDownTimer != null) {
            mCountDownTimer.cancel();
            mCountDownTimer = null;
        }
        // 发送网络请求
        mRxManager.add(ApiRequest.requestCommitAnswer(mUserInfo.getJwt(),
                mUserInfo.getTestTask().getTestTaskId()+"", mUsedTime, mQuestionList)
                .subscribe(new RxSubscriber<String>(mContext) {
                    @Override
                    protected void _onNext(String msg) {
                        // 响应处理
                        if (GsonUtils.getIntValue(msg, "error") == 0) {
                            ToastUtils.showShort("提交答案成功");
                            // 解析响应
                            String result = GsonUtils.getValue(msg, "result");
                            TestResult testResult = (TestResult) GsonUtils.fromJson(result, TestResult.class);
                            // 保存测评结果
                            ((AppApplication)getApplicationContext()).setTestResult(testResult);
                            // 显示第二页
                            mPagerTwoSumText.setText("315/315");
                            mPagerTwoTimeText.setText("剩余时间: " + mRemainTime);
                            mPagerTwoResultImage.setImageResource(R.drawable.ic_test_success);
                            switchPagerTo(2);
                        } else {
                            String reason = GsonUtils.getValue(msg, "reason");
                            ApiConstants.showError(reason);
                        }
                    }

                    @Override
                    protected void _onError(String message) {
                        // TODO:处理失败响应
                        ToastUtils.showShort("提交答案失败:" + message);
                    }
                }));

    }

    // 查看测评结果(PageThree)
    @OnClick(R.id.btn_exit)
    public void clickExit() {
        // 跳转到测评结果页面
        ActTransAnimUtils.startActionSlideRightToLeft(MainActivity.this, TestResultActivity.class);
        finish();
    }

    /*--------------------------------------------------------------------------------
     *                          Activity的生命周期接口处理
     ---------------------------------------------------------------------------------*/
    @Override
    protected void onStart() {
        super.onStart();
        if (AppCommonUtils.isAppOnForeground()) {
            if (mCountDownTimer != null) {
                mCountDownTimer.start();
            }
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (!AppCommonUtils.isAppOnForeground()) {
            if (mCountDownTimer != null) {
                mCountDownTimer.stop();
            }
        }
    }
}
